/**
 * 切换前后台获取地理位置信息
 * **/
const getLocation = () => {
  return new Promise((resolve, reject) => {
    const locationChangeFn = (res) => {
      resolve(res)
    }

    // 前后台定位
    const startLocationUpdateBackground = () => {
      wx.startLocationUpdateBackground({
        success: (res) => {
          wx.onLocationChange(locationChangeFn)
        }
      })
    }

    // 前台定位
    const startLocationUpdate = () => {
      wx.startLocationUpdate({
        success: (res) => {
          wx.onLocationChange(locationChangeFn)
        },
        fail: (err) => {
          console.log(err)
        }
      })
    }

    // 授权
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userLoactionBackground']) { 
          // 前后台定位 
          startLocationUpdateBackground()
        } else if(res.authSetting['scope.userLocation']) {
          // 前台定位
          startLocationUpdate()
        } else {
          wx.showModal({
            content: '需要获取前后台运行定位权限',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting({
                  success: (res) => {
                    if (res.authSetting['scope.userLocationBackground']) {
                      // 前后台定位 
                      startLocationUpdateBackground()
                    }else if(res.authSetting['scope.userLocation']) {
                      // 前台定位
                      startLocationUpdate()
                    } else {
                      wx.showToast({
                        title: '不能获取定位',
                      })
                    }
                  },
                  fail: (err) => {
                    wx.showToast({
                      title: '不能获取定位',
                    })
                  }
                })
              } else {
                wx.showToast({
                  title: '不能获取定位',
                })
              }
            }
          })
        }
      }
    })
  })
}

module.exports = {
  getLocation
}

